//
//  ViewController.swift
//  WebImageDemo
//
//  Created by Apple on 2018/5/24.
//  Copyright © 2018年 Apple. All rights reserved.
//

import UIKit


public typealias ViewControllerWebViewContentHeightChanged = (CGFloat) -> Void

let HTMLHEADER  = "<html><head><meta name=\"viewport\" content=\"width=device-width, user-scalable=no\">"
let jsCode = try! String(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "JSTools", ofType: "js")!))

class ViewController: UIViewController {

    var tapGesture: UITapGestureRecognizer?
    weak var parentScrollView: UIScrollView? {
        didSet {
            //滑动的时候，点击不生效
            tapGesture?.require(toFail: self.parentScrollView!.panGestureRecognizer)
        }
    }
    
    var contentHeightChanged: ViewControllerWebViewContentHeightChanged?
     var contentHeight : CGFloat = 0
    
    // MARK: - System methdos
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        viewBindEvents()
    }
    
    // MARK: - Private methods
    func setupUI() {
        
        //这里有一个问题，
        
        //如果baseURL 设置为nil，则可以直接引用本地css文件。
        //但不能加载 地址 //:开头的 的图片。
        
        //如果将baseUrl 设为 http/https ，则可以加载图片。但是却不能直接引用本地css文件，
        //因为WebView 有同源限制，http/https 与 我们本地css文件的 file:// 是不同源的
        //所以就会导致 css 样式不能加载
        
        //所以这里做个了折中方案，baseUrl 使用https ,将css样式写进html。
        
//        let style = "<style>" + V2Style.sharedInstance.CSS + "</style></head>"
//        html =  HTMLHEADER + style  + html + "</html>"
//
//        self.webView.loadHTMLString(html, baseURL: URL(string: "https://"))
        
        guard let url = URL.init(string: "http://www.vcb.cn") else {
            return
        }
    
        webView.delegate = self
        webView.loadRequest(URLRequest.init(url: url))
        self.view.addSubview(webView)
    }
    
    func viewBindEvents() {
        
        // 通过kvo监听网页的高度 pod 'KVOController', '~> 1.2.0'
//        self.kvoController.observe(self.webView.scrollView, keyPath: "contentSize", options: [.new]) {
//            [weak self] (observe, observer, change) -> Void in
//            if let weakSelf = self {
//                let size = change["new"] as! NSValue
//                weakSelf.contentHeight = size.cgSizeValue.height;
//                weakSelf.contentHeightChanged?(weakSelf.contentHeight)
//            }
//        }
        
        tapGesture = UITapGestureRecognizer(target: self, action:#selector(tapHandler(_:)))
        self.tapGesture!.delegate = self
        self.webView.addGestureRecognizer(self.tapGesture!);
    }
    
    @objc func tapHandler(_ tap : UITapGestureRecognizer) {
        
        let tapPoint = tap.location(in: tap.view)
        let script = String(format: "javascript:getHTMLElementAtPoint('%f','%f')", Int(tapPoint.x),Int(tapPoint.y))
        
        //let script = "javascipt:getImages()"
        
        let imgSrc = self.webView.stringByEvaluatingJavaScript(from: script)
        guard let img = imgSrc , img.count > 0 else {
            return
        }
        let arr = img.components(separatedBy: ",")
        //print(arr)
        guard arr.count == 5 else {
            return
        }
        let url = fixUrl(url: arr[0])
//        let width = Int(arr[1])
//        let height = Int(arr[2])
//        let left = Int(arr[3])
//        let top = Int(arr[4])
//        guard let w = width ,let h = height , let l = left , let t = top else {
//            return;
//        }
        print(url)
        
    }
    private func fixUrl(url: String) -> String {
        if(url.hasPrefix("http") || url.hasPrefix("https")){
            return url
        }
        if (url.hasPrefix("//")){
            return "https:" + url
        }
        else if(url.hasPrefix("/")){
            return "https://www.v2ex.com" + url
        }
        else {
            return url
        }
    }
    
    // MARK: - Lazy load
    lazy var webView: UIWebView = UIWebView.init(frame: UIScreen.main.bounds)

}

extension ViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        self.webView.stringByEvaluatingJavaScript(from: jsCode)
        
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        return true
    }
    
}

extension ViewController: UIGestureRecognizerDelegate {
    //让点击图片手势 和webView的手势能共存
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

